using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.presentation.cache;
using umbraco.uicontrols;
using umbraco.controls;
using Commerce.Common;
using System.Text.RegularExpressions;

namespace CommerceForUmbraco.adminSection.commerce
{
    /// <summary>
    /// Edit Category
    /// </summary>
    public partial class editCategory : umbraco.BasePages.UmbracoEnsuredPage
    {
        #region properties

        public TabPage MainTab;
        public TabPage ImageTab;

        //Media Pickers
        private umbraco.editorControls.mediaChooser _mediaPicker;
        private MediaPickerDataExtractor _mediaPickerExtractor;

        // Category
        Category thisCat;

        #endregion

        protected string GenerateUrlFriendlyName(string name)
        {
            string slug;

            slug = Regex.Replace(name, @"[\?\!:\$""&']", String.Empty);

            slug = Regex.Replace(slug, @"[\.]", "_");

            slug = slug.Replace(' ','-');

            return slug;
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            string categoryId = Request.QueryString.Get("c");
            thisCat = new Category(int.Parse(categoryId));

            if (!IsPostBack)
            {
                CategoryName.Text = thisCat.CategoryName;
                if (thisCat.UrlFriendly.Length > 0)
                {
                    CategorySlug.Text = thisCat.UrlFriendly;
                }
                else
                {
                    CategorySlug.Text = GenerateUrlFriendlyName(thisCat.CategoryName);
                }
                shortDescription.Text = thisCat.ShortDescription;
                longDescription.Text = thisCat.LongDescription;

                if (ParentCategory.Items != null)
                {
                    // parent category
                    CategoryCollection categories = new CategoryCollection().OrderByAsc("CategoryName").Load();
                    ParentCategory.Items.Clear();
                    ParentCategory.Items.Add(new ListItem("None", "0"));
                    foreach (Category prntCat in categories)
                    {
                        if (prntCat.CategoryID != thisCat.CategoryID)
                        {
                            ParentCategory.Items.Add(new ListItem(prntCat.CategoryName, prntCat.CategoryID.ToString()));
                        }
                    }
                    ParentCategory.SelectedIndex = ParentCategory.Items.IndexOf(ParentCategory.Items.FindByValue(thisCat.ParentID.ToString()));
                }

                ListOrder.Text = thisCat.ListOrder.ToString();

                // image media
                _mediaPicker.Value = thisCat.ImageFile;
                int mediaId;
                if (Int32.TryParse(_mediaPicker.Value.ToString(), out mediaId))
                {
                    if (mediaId > 0)
                    {
                        if (umbraco.cms.businesslogic.media.Media.IsNode(mediaId))
                        {
                            umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(mediaId);
                            if (m != null)
                            {
                                productImageView.ImageUrl = String.Format("/umbraco/ImageGen.ashx?image={0}&height=300&width=300&antialias=true&format=png&constrain=true", m.getProperty("umbracoFile").Value.ToString());
                            }
                        }
                    }
                }
            }

            //this.Panel1.Text = "Edit Category";

            // Main Tab Labels
            this.Pane7.Text = "Edit Category";
            this.pp_name.Text = "Category Name";
            this.pp_slug.Text = "URL Identifier";
            this.pp_parent.Text = "Parent Category";
            this.pp_ListOrder.Text = "List Order";
            this.pp_short_description.Text = "Short Description";
            this.pp_long_description.Text = "Long Description";

            // Image Tab Labels
            this.Pane3.Text = "Product Image";
            this.pp_images.Text = "Image";

        }

        private void InitializeComponent()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            // Tab setup
            MainTab = tabControl.NewTabPage("Main");
            MainTab.Controls.Add(Pane7);

            ImageTab = tabControl.NewTabPage("Image");
            ImageTab.Controls.Add(Pane3);

            // Main Tab
            ImageButton save = MainTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Images Tab
            ImageButton save3 = ImageTab.Menu.NewImageButton();
            save3.Click += new ImageClickEventHandler(this.save_click);
            save3.AlternateText = "Save";
            save3.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            //ImageButton button = this.Panel1.Menu.NewImageButton();
            //button.Click += new ImageClickEventHandler(this.save_click);
            //button.AlternateText = "Save";
            //button.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";


            //Media Pickers
            _mediaPickerExtractor = new MediaPickerDataExtractor();
            _mediaPicker = new umbraco.editorControls.mediaChooser(_mediaPickerExtractor);
            _mediaPicker.ID = "mediapicker";
            pnlMediaPicker.Controls.Add(_mediaPicker);


            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);
        }

        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveCategory(this.CategoryName.Text, base.Request.QueryString["c"]))
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemSaved"), "");
            }
            else
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "commerceItemErrorText"));
            }
        }

        private bool SaveCategory(string categoryName, string categoryId)
        {
            try
            {
                int catId;
                Category cat;
                if (Int32.TryParse(categoryId, out catId))
                {
                    cat = new Category(catId);

                    int _parentID;

                    cat.CategoryName = categoryName;
                    cat.UrlFriendly = this.CategorySlug.Text;
                    cat.ParentID = Int32.TryParse(this.ParentCategory.SelectedItem.Value, out _parentID) ? _parentID : 0;
                    cat.ShortDescription = shortDescription.Text;
                    cat.LongDescription = longDescription.Text;

                    int lo = 99;
                    if (Int32.TryParse(ListOrder.Text, out lo) == true)
                    {
                        cat.ListOrder = lo;
                    }
                    
                    // image
                    if (_mediaPicker.Value != "")
                    {
                        int mediaID;

                        if (Int32.TryParse(_mediaPicker.Value, out mediaID))
                        {
                            if (mediaID > 0)
                            {
                                if (umbraco.cms.businesslogic.media.Media.IsNode(mediaID))
                                {
                                    umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(mediaID);

                                    if (m != null)
                                    {
                                        cat.ImageFile = m.Id.ToString();
                                        // also create a record in CSK_Store_Image - dashCommerce legacy requirement
                                        //Commerce.Common.Image img = new Commerce.Common.Image(true);
                                        //img.ImageFile = m.Id.ToString();
                                        //img.Caption = cat.CategoryName;
                                        //img.ProductID = cat.CategoryID;
                                        //ImageCollection productImages = new ImageCollection().Load();
                                        //productImages.Clear();
                                        //productImages.Add(img);
                                        //productImages.SaveAll("Commerce for Umbraco");
                                    }
                                }
                            }
                        }
                    }

                    cat.Save();
                }

                return true;
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));

                return false;
            }
        }

    }
}
 
